package com.gogowan.agroenterprise.newview;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import com.gogowan.agroenterprise.MyApplication;
import com.gogowan.agroenterprise.R;
import com.gogowan.agroenterprise.barcode.Intents;
import com.gogowan.agroenterprise.base.BaseActivity;
import com.gogowan.agroenterprise.contorl.MyAsyncTask;
import com.gogowan.agroenterprise.model.BoxCode;
import com.gogowan.agroenterprise.model.DealerListResult;
import com.gogowan.agroenterprise.model.DealerModel;
import com.gogowan.agroenterprise.model.DealerRequest;
import com.gogowan.agroenterprise.model.OutStorageBoxRequest;
import com.gogowan.agroenterprise.model.OutStorageBoxResult;
import com.gogowan.agroenterprise.model.OutStorageReault;
import com.gogowan.agroenterprise.model.OutStorageRequest;
import com.gogowan.agroenterprise.model.UserType;
import com.gogowan.agroenterprise.utils.DialogUitl;
import com.gogowan.agroenterprise.utils.INewAdapterClick;
import com.gogowan.agroenterprise.utils.ListDataSave;
import com.gogowan.agroenterprise.utils.NetWorkManger;
import com.gogowan.agroenterprise.utils.SystemBroadCast;
import com.gogowan.agroenterprise.utils.ToastUtils;
import com.gogowan.agroenterprise.utils.Utils;
import com.gogowan.agroenterprise.widget.adapter.HwScanAdapter;
import com.gogowan.agroenterprise.widget.adapter.NewInXMListViewAdapter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ioid.utils.JsonUtils;
import com.ioid.utils.StringUtils;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Debug;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * 出库
 *
 * @author tjh 2017-01-13
 */
public class NewOutStorageActivity extends BaseActivity implements OnClickListener {
    private ProgressDialog progressDialog;

    ListDataSave<String> dataSave;
    private TextView dhEdit;
    private Spinner jxsSpinner;
    // private DealerSpinnerAdapter jxsSpinnerAdapter;
    private List<DealerModel> dealerList = new ArrayList<DealerModel>();
    private ArrayList<String> dealerListName = new ArrayList<String>();
    private ArrayAdapter<String> adapter;

    private ListView xmListView;
    //    private NewInXMListViewAdapter xMListViewAdapter;
    private HwScanAdapter stringAdapater;
    private List<BoxCode> boxCodeList = new ArrayList<BoxCode>();
    // 总的list
    private List<String> codeStringList = new ArrayList<>();
    // 扫码返回的list
    private ArrayList<String> resultStringList;
    private Calendar cal;
    private int year, month, day;
    private DatePickerDialog datePickerDialog;
    private Button btnXSSJ;
    private boolean isHeadBack=true;
    private TextView SC_Tv;
    private Handler myHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    adapter.notifyDataSetChanged();
                    break;
                case 1:
                    break;
                case 2:
//				xMListViewAdapter.notifyDataSetChanged();
//				SC_Tv.setText(boxCodeList.size()+"个码");
                    SC_Tv.setText(codeStringList.size() + "");
                    break;
                default:
                    break;
            }
        }
    };
    private OutStorageRequest outStorageRequest;
    private EditText xsbz;
    private int usertype;
    private long userId;
    private int jxsPosition;
    private String username;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.new_activity_out_storage);
        dataSave=new ListDataSave<>();
        initDateDialog();
        initView();
        initValue();
        usertype = MyApplication.mSettings.getInt("usertype", 1);
        userId=MyApplication.mSettings.getLong("personid",0);
        username=MyApplication.mSettings.getString("username","");
        List<String> dataList = dataSave.getDataList(userId+MyApplication.NEW_OUT_STORAGE);
        if(dataList!=null&&dataList.size()>0){
            codeStringList.addAll(dataList);
            SC_Tv.setText(codeStringList.size() + "");
        }
        if (Debug.isDebuggerConnected()) {
            codeStringList.add("MA.156.M0.100366.0c0116727025.S0125117.M230320.L20230357.V260319.C7");
            SC_Tv.setText(codeStringList.size() + "");
        }

    }

    private void initDateDialog() {
        cal = Calendar.getInstance();
        year = cal.get(Calendar.YEAR); // 获取年月日时分秒
        month = cal.get(Calendar.MONTH); // 获取到的月份是从0开始计数
        day = cal.get(Calendar.DAY_OF_MONTH);
    }

    /**
     * 初始化界面
     */
    private void initView() {
        SC_Tv = (TextView) findViewById(R.id.scancount_tv);
        // 经销商
        jxsSpinner = (Spinner) findViewById(R.id.out_storage_jxs_spinner);
        jxsSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                // TODO Auto-generated method stub
                jxsPosition=position;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // TODO Auto-generated method stub

            }
        });

        // jxsSpinnerAdapter = new DealerSpinnerAdapter(this, dealerList);
        // jxsSpinner.setAdapter(jxsSpinnerAdapter);
        // 修改adapter样式
        adapter = new ArrayAdapter<String>(NewOutStorageActivity.this, R.layout.simple_spinner_item1, dealerListName) {

            @Override
            public View getDropDownView(int position, View convertView, ViewGroup parent) {
                View view = View.inflate(getContext(), R.layout.new_activity_store_spinner_item, null);
                TextView label = (TextView) view.findViewById(R.id.store_spinner_item_ckmc_text);
                ImageView check = (ImageView) view.findViewById(R.id.store_spinner_item_ckmc_cb);
                label.setText(dealerListName.get(position));
                if (jxsSpinner.getSelectedItemPosition() == position) {
                    check.setImageResource(R.drawable.invent_select);
                    // viewHolder.selectBtn.setVisibility(View.GONE);
                } else {
                    check.setImageResource(R.drawable.invent_noselect);
                }
                return view;
            }
        };

        adapter.setDropDownViewResource(R.layout.new_activity_store_spinner_item);
        jxsSpinner.setAdapter(adapter);
        xmListView = (ListView) findViewById(R.id.out_storage_xmlist);
//        xMListViewAdapter = new NewInXMListViewAdapter(this, boxCodeList, 2);
        stringAdapater = new HwScanAdapter(this, codeStringList, new INewAdapterClick() {
            @Override
            public void onItemClick(View view, final int position) {
                //点击删除回调接口
                DialogUitl.showDeleteDailog(
                        NewOutStorageActivity.this,
                        codeStringList.get(position),
                        (codeStringList.size() - position) + "", new DialogUitl.DialogClickCallBack() {
                            @Override
                            public void okButtonClick() {
                                codeStringList.remove(position);
                                stringAdapater.notifyDataSetChanged();
                                SC_Tv.setText(codeStringList.size() + "");
                            }

                            @Override
                            public void cancleButtonClick() {

                            }
                        });

            }
        });
        xmListView.setAdapter(stringAdapater);
//		xmListView.setOnItemClickListener(new OnItemClickListener() {
//
//			@Override
//			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//				Intent itent = new Intent(NewOutStorageActivity.this, NewInOutDetailActivity.class);
//				itent.putExtra("item", boxCodeList.get(position));
//				startActivity(itent);
//			}
//
//		});
        SC_Tv.setText(boxCodeList.size() +"");
        ImageButton fhBtn = (ImageButton) findViewById(R.id.out_storage_fh_btn);
        fhBtn.setOnClickListener(this);
        dhEdit = (TextView) findViewById(R.id.out_storage_dh_edit);
        ImageView smhqdhBtn = (ImageView) findViewById(R.id.out_storage_smhqdh_btn);
        smhqdhBtn.setOnClickListener(this);
        Button smrkxmBtn = (Button) findViewById(R.id.out_storage_smrkxm_btn);
        smrkxmBtn.setOnClickListener(this);
        Button qrrkBtn = (Button) findViewById(R.id.out_storage_qrck_btn);
        qrrkBtn.setOnClickListener(this);
        Button smrkxmBtnhw = (Button) findViewById(R.id.out_storage_smrkxm_btn_hw);
        smrkxmBtnhw.setOnClickListener(this);
        btnXSSJ = (Button) findViewById(R.id.xssj);
        xsbz = (EditText) findViewById(R.id.xsbz);
        btnXSSJ.setOnClickListener(this);
        datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                String str = year + "-" + (monthOfYear + 1) + "-" + dayOfMonth;
                btnXSSJ.setText(str);
            }
        }, year, month, day);
        initScanView(new SystemBroadCast.ScanResultListener() {
            @Override
            public void OnResult(String CodeString) {
                if (isVisible) {
                    dhEdit.setText(CodeString);
                }
            }
        });
        findViewById(R.id.btn_clear).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(codeStringList.size()<=0){
                    Toast.makeText(NewOutStorageActivity.this,"请先扫码",Toast.LENGTH_LONG).show();
                    return;
                }
                DialogUitl.showTongyongSubmitDailog(NewOutStorageActivity.this,
                        "提示","您确定清空"+codeStringList.size()+"条扫码记录嘛？", new DialogUitl.DialogClickCallBack() {
                            @Override
                            public void okButtonClick() {

                                codeStringList.clear();
                                stringAdapater.notifyDataSetChanged();
                                SC_Tv.setText(codeStringList.size() + "");
                                dataSave.setDataList(userId+MyApplication.NEW_OUT_STORAGE,new ArrayList<String>());
                            }

                            @Override
                            public void cancleButtonClick() {

                            }
                        });

            }
        });
    }

    /**
     * 初始化数据
     */
    private void initValue() {
        if (MyApplication.mSettings.getInt("usertype", 0) == UserType._JING_XIAO_SHANG.getTypeID()) {
            findViewById(R.id.time_ll).setVisibility(View.GONE);
        }
        progressDialog = ProgressDialog.show(this, getString(R.string.alert_title), getString(R.string.alert_message),
                true, false);

        DealerRequest dealerRequest = new DealerRequest();

        GetDealerListAsyn getDealerListAsyn = new GetDealerListAsyn();
        getDealerListAsyn.execute(dealerRequest);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode==KeyEvent.KEYCODE_BACK){

        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        Intent intent;
        switch (v.getId()) {
            case R.id.xssj:
                datePickerDialog.show();
                break;
            case R.id.out_storage_fh_btn:
                // 返回
                this.finish();
                break;
            case R.id.out_storage_smhqdh_btn:
                // 扫码获取单号
                intent = new Intent(Intents.Scan.ACTION);
                this.startActivityForResult(intent, 10);
                break;
            case R.id.out_storage_smrkxm_btn:
                // 扫描入库箱码
                intent = new Intent(Intents.Scan.ACTION);
                intent.putExtra(Intents.Scan.IS_BULT_MODE, true);
                this.startActivityForResult(intent, 20);
                break;
            case R.id.out_storage_smrkxm_btn_hw://红外扫码
                intent = new Intent(NewOutStorageActivity.this, HWDialogActivity.class);
                intent.putExtra("type", "lx");
                this.startActivityForResult(intent, 505);
                break;
            case R.id.out_storage_qrck_btn:
                // 确认入库
                /*
                 * if (TextUtils.isEmpty(dhEdit.getText())) { Toast.makeText(this,
                 * "请输入单号", 200).show(); } else
                 */
                if (codeStringList.size() < 1) {
                    showToast("请扫描出库码!");
                    return;
                }
                if (jxsPosition==0) {
                    showToast("请选择经销商!");
                    return;
                }
                boolean b = NetWorkManger.hasNet(getApplicationContext());
                if(b)
                    DialogUitl.showTishiDailog(NewOutStorageActivity.this,
                            codeStringList.size() + "",
                            new DialogUitl.DialogClickCallBack() {
                                @Override
                                public void okButtonClick() {
                                    SaveHttp();
                                }

                                @Override
                                public void cancleButtonClick() {

                                }
                            });
                else
                    ToastUtils.show(getApplicationContext(),"暂无网络");

//			new AlertDialog.Builder(NewOutStorageActivity.this)
//					.setTitle("提示")
//					.setMessage("您是否确定要提交数据？")
//					.setNegativeButton("确定", new DialogInterface.OnClickListener() {
//						@Override
//						public void onClick(DialogInterface dialog, int which) {
////							if (boxCodeList.size() <= 0) {
//							if (codeStringList.size()<=0){
//								Toast.makeText(NewOutStorageActivity.this, "请扫描出库码", Toast.LENGTH_SHORT).show();
//							} else {
//								progressDialog = ProgressDialog.show(NewOutStorageActivity.this, getString(R.string.alert_title),
//										getString(R.string.alert_message), true, false);
//
//								outStorageRequest = new OutStorageRequest();
//								StringBuffer sb=new StringBuffer();
//								for (int i = 0; i < codeStringList.size(); i++) {
//									sb.append(codeStringList.get(i));
//									if(i!=codeStringList.size()-1){
//										sb.append(",");
//									}
//								}
//								outStorageRequest.setCodes(sb.toString());
//								outStorageRequest.setPersonid(MyApplication.mSettings.getLong("personid",0)+"");
//								outStorageRequest.setSupplierId(jxsID+"");
//								OutStorageYanAsyn outStorageAsyn = new OutStorageYanAsyn();
//								outStorageAsyn.execute(outStorageRequest);
//							}
//						}
//					})
//					.setNeutralButton("取消", new DialogInterface.OnClickListener() {
//						@Override
//						public void onClick(DialogInterface dialog, int which) {
//
//						}
//					})
//					.show();
                break;
            default:
                break;
        }
    }

    private void SaveHttp() {
        progressDialog = ProgressDialog.show(NewOutStorageActivity.this, getString(R.string.alert_title),
                getString(R.string.alert_message), true, false);

        outStorageRequest = new OutStorageRequest();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < codeStringList.size(); i++) {
            sb.append(codeStringList.get(i));
            if (i != codeStringList.size() - 1) {
                sb.append(",");
            }
        }
        outStorageRequest.setRemark(xsbz.getText().toString());
        outStorageRequest.setCodes(sb.toString());
        outStorageRequest.setPersonid(userId + "");
        outStorageRequest.setSupplierId(dealerList.get(jxsPosition).getId() + "");
        if(usertype==UserType._GONG_CHANG.getTypeID()){
            //1代表工厂
            OutStorageYanAsyn outStorageAsyn = new OutStorageYanAsyn();
            outStorageAsyn.execute(outStorageRequest);

        }else{
            //其他代表是经销商
            OutStorageJXSAsyn outStorageAsyn = new OutStorageJXSAsyn();
            outStorageAsyn.execute(outStorageRequest);
            Toast.makeText(getApplicationContext(), "出库成功",
                    Toast.LENGTH_LONG).show();
            progressDialog.dismiss();
            isHeadBack=false;
            NewOutStorageActivity.this.finish();
        }



    }

    private List<String> GetList() {
        List<String> arr = new ArrayList<>();
        for (BoxCode boxCode : boxCodeList) {
            arr.add(boxCode.getCode());
        }
        return arr;
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            String codeStr="";
            switch (requestCode) {
                case 10:
                    // 扫码获取单号
                    if(data!=null)
                        codeStr = data.getStringExtra(Intents.Scan.RESULT);
                    dhEdit.setText(codeStr);
                    break;
                case 20:
                case 505:
                    // 扫描入库箱码
                    if(data!=null)
                        resultStringList = data.getStringArrayListExtra(Intents.Scan.RESULTLIST);
                    else
                        resultStringList=new ArrayList<>();
                    for (int i = 0; i < resultStringList.size(); i++) {
                        if (resultStringList.get(i).contains("=")) {
                            String s = resultStringList.get(i);
                            s = s.substring(s.indexOf("=") + 1);
                            resultStringList.set(i, s);
                        }
                        String result = resultStringList.get(i);

                        result=result.replaceAll("\n","");
                        String[] parts = result.split("MA.156.M0");
                        if (parts.length >= 3) {//"包含2个以上\"MA.156.M0\""
                            //有多个数据
                            for (int j = 0; j < parts.length; j++) {
                                if (j==1){
                                    if (!resultStringList.contains("MA.156.M0"+parts[1])){
                                        resultStringList.set(i,"MA.156.M0"+parts[1]);
                                    }
                                }else if(j>1){
                                    if (!resultStringList.contains("MA.156.M0"+parts[j])){
                                        resultStringList.add(i+j+1-2,"MA.156.M0"+parts[j]);
                                    }
                                }
                            }
                        }
                    }
                    if (resultStringList.size() == 0) {
                        return;
                    }
                    codeStringList.addAll(0,GetOneList());
                    codeStringList = codeStringList.stream().distinct().collect(Collectors.toList());
                    myHandler.sendEmptyMessage(2);
                    stringAdapater.setList(codeStringList);
                    stringAdapater.notifyDataSetChanged();
//				progressDialog = ProgressDialog.show(this, getString(R.string.alert_title),
//						getString(R.string.alert_message), true, false);
//
//				OutStorageBoxRequest outStorageBoxRequest = new OutStorageBoxRequest();
//				outStorageBoxRequest.setEnterpriseId((MyApplication.mSettings.getInt("usertype",0)==2?loginResultInfo.getEnterpriseinfo().getDealerId():loginResultInfo.getEnterpriseinfo().getEnterpriseid()));
//				outStorageBoxRequest.setBoxCode(resultStringList);
//
//                    OutStorageListAsyn outStorageListAsyn = new OutStorageListAsyn();
//				outStorageListAsyn.execute(outStorageBoxRequest);
                    break;
                default:
                    break;
            }
        }
    }

    private List<String> GetOneList() {
        List<String> strings = new ArrayList<>();

        for (String str : resultStringList) {
            if (!codeStringList.contains(str.trim()) && str.startsWith("MA.156.M0")) {
                strings.add(str.trim());
            }
        }
        if (strings.size() < 1 && resultStringList.size() > 0) {
            showToast("该组码内容重复扫码或者错误码");
        } else if (strings.size() != resultStringList.size()) {
            showToast("存在重复扫码，已自动过滤");
        }
        return strings;
    }

    /**
     * 获取经销商列表
     *
     * @author tjh
     */
    private class GetDealerListAsyn extends MyAsyncTask {

        @Override
        protected void onPostExecute(Object res) {
            if (res == null || res.equals("")) {
                Toast.makeText(NewOutStorageActivity.this, getString(R.string.server_error), Toast.LENGTH_LONG).show();
            } else {
                try {
                    JSONObject jo = new JSONObject(res.toString());
                    if (jo.getInt("code") != 200) {
                        Toast.makeText(getApplicationContext(), jo.getString("msg"), Toast.LENGTH_LONG).show();
                        return;
                    }
                    res = jo.getJSONArray("data").toString();
                } catch (Exception e) {

                }
                if (res == null || res.equals("")) {
                    Toast.makeText(NewOutStorageActivity.this, getString(R.string.analyse_error), Toast.LENGTH_LONG)
                            .show();
                } else {
                    Type userListType = new TypeToken<List<DealerModel>>() {
                    }.getType();
                    List<DealerModel> storeListResult = (List<DealerModel>) JsonUtils.fromJSON(res.toString(), userListType);
                    if (storeListResult != null&&storeListResult.size() > 0) {
                        dealerList.clear();
                        dealerListName.clear();
                        dealerListName.add("请选择");
                        dealerList.add(new DealerModel());
                        for (int i = 0; i < storeListResult.size(); i++) {
                            dealerList.add(storeListResult.get(i));
                            dealerListName.add(storeListResult.get(i).getSupplier());
                        }
                        myHandler.sendEmptyMessage(0);
                    } else {
                        ToastUtils.show(getApplicationContext(), "暂无数据");
                    }
                }
            }
            progressDialog.dismiss();
            super.onPostExecute(res);
        }

        @Override
        protected Object doInBackground(Object... params) {
//            String userID="";
//            if(usertype==UserType._GONG_CHANG.getTypeID()){
//                String token = MyApplication.mSettings.getString("token", "");
//                if(!StringUtils.isEmpty(token)&&token.split("_").length>=2){
//                    userID=token.split("_")[1];
//                }
//
//            }else{
//                userID=MyApplication.mSettings.getLong("personid",0)+"";
//            }
            String res = Utils.getCommit(getString(R.string.first_url)
                    + getString(R.string.getSupplierList) + "?personid=" + userId);
            return res;
        }
    }

//    /**
//     * 箱码列表
//     *
//     * @author tjh
//     */
//    private class OutStorageListAsyn extends MyAsyncTask {
//
//        @Override
//        protected void onPostExecute(Object res) {
//            if (res == null || res.equals("")) {
//                Toast.makeText(NewOutStorageActivity.this, getString(R.string.server_error), Toast.LENGTH_LONG).show();
//            } else {
//                com.gogowan.agroenterprise.model.Message message = (com.gogowan.agroenterprise.model.Message) Utils
//                        .fromJSON((String) res, com.gogowan.agroenterprise.model.Message.class);
//                String string = Utils.getMessageContent(message);
//
//                if (string == null || string.equals("")) {
//                    Toast.makeText(NewOutStorageActivity.this, getString(R.string.analyse_error), Toast.LENGTH_LONG)
//                            .show();
//                } else {
//                    OutStorageBoxResult outStorageBoxResult = (OutStorageBoxResult) Utils.fromJSON(string,
//                            OutStorageBoxResult.class);
//                    if (outStorageBoxResult.getResult() == 15000) {
//                        if (outStorageBoxResult.getBoxInfo() != null) {
//                            boxCodeList.addAll(outStorageBoxResult.getBoxInfo());
//                            codeStringList.addAll(resultStringList);
//                            myHandler.sendEmptyMessage(2);
//                        }
//                    } else {
//                        Toast.makeText(NewOutStorageActivity.this, outStorageBoxResult.getResultinfo(),
//                                Toast.LENGTH_LONG).show();
//                    }
//                }
//            }
//            progressDialog.dismiss();
//            super.onPostExecute(res);
//        }
//
//        @Override
//        protected Object doInBackground(Object... params) {
//            OutStorageBoxRequest outStorageBoxRequest = (OutStorageBoxRequest) params[0];
//            String json = Utils.toJSON(outStorageBoxRequest);
//            Log.i("gggggggggggggggggg===", json);
//            com.gogowan.agroenterprise.model.Message message = new com.gogowan.agroenterprise.model.Message((MyApplication.mSettings.getInt("usertype", 0) == UserType._JING_XIAO_SHANG.getTypeID() ? 19001 : 19000), true,
//                    json);
//            String ss = Utils.toJSON(message);
//            Log.i("gggggggggggggggggg===", ss);
//            String res = Utils.postCommit(getString(R.string.first_url) + getString(R.string.first_url_page), message);
//            return res;
//        }
//    }

    /**
     * 确认出库请求
     *
     * @author tjh
     */
    private class OutStorageAsyn extends MyAsyncTask {

        @Override
        protected void onPostExecute(Object res) {

            //获取提交请求
            String str=Utils.toJSON(outStorageRequest);
            JSONObject data1 =null;
            if (res == null || res.equals("")) {
                data1 = Utils.getDiffData(0,"出库提交", "与服务器通讯失败", username, str);
                Toast.makeText(NewOutStorageActivity.this, getString(R.string.server_error), Toast.LENGTH_LONG).show();
            } else {
                try {
                    JSONObject jo = new JSONObject(res.toString());
                    data1 = Utils.getDiffData(jo.getInt("code"),"出库提交", jo.getString("msg"), username, str);

                } catch (Exception e) {
                    e.printStackTrace();
                    data1 = Utils.getDiffData(0, "出库提交","数据解析失败！", username, str);
                }
            }
            String jaString = MyApplication.mSettings.getString(MyApplication.ALL_LOGS, "");
            try {
                JSONArray ja=null;
                if(StringUtils.isEmpty(jaString)){
                    ja=new JSONArray();
                }else{
                    ja=new JSONArray(jaString);

                }
                data1.put("usertype",usertype);

                ja.put(data1);
                MyApplication.editor.putString(MyApplication.ALL_LOGS,ja.toString());
                MyApplication.editor.commit();

            } catch (JSONException e) {
                e.printStackTrace();
            }
            super.onPostExecute(res);
        }

        @Override
        protected Object doInBackground(Object... params) {
            OutStorageRequest outStorageRequest = (OutStorageRequest) params[0];

            String res = Utils.postCommit(getString(R.string.first_url) + getString(R.string.addDepotHeadAndDetailAPP), outStorageRequest);
            return res;
        }
    }

    /**
     * 出库请求验证
     *
     * @author tjh
     */
    private class OutStorageYanAsyn extends MyAsyncTask {

        @Override
        protected void onPostExecute(Object res) {
            progressDialog.dismiss();

            //获取提交请求
            String str=Utils.toJSON(outStorageRequest);
            JSONObject data1 =null;
            if (res == null || res.equals("")) {
                data1 = Utils.getDiffData(0,"出库校验", "与服务器通讯失败", username, str);
                Toast.makeText(NewOutStorageActivity.this, getString(R.string.server_error), Toast.LENGTH_LONG).show();
            } else {
                try {
                    JSONObject jo = new JSONObject(res.toString());
                    Toast.makeText(getApplicationContext(), jo.getString("msg"),
                            Toast.LENGTH_LONG).show();
                    data1 = Utils.getDiffData(jo.getInt("code"),"出库校验", jo.getString("msg"), username, str);
                    if (jo.getInt("code") == 200) {
                        OutStorageAsyn outStorageAsyn = new OutStorageAsyn();
                        outStorageAsyn.execute(outStorageRequest);
                        isHeadBack=false;
                        NewOutStorageActivity.this.finish();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    data1 = Utils.getDiffData(0, "出库校验","数据解析失败！", username, str);
                }
            }
            String jaString = MyApplication.mSettings.getString(MyApplication.ALL_LOGS, "");
            try {
                JSONArray ja=null;
                if(StringUtils.isEmpty(jaString)){
                    ja=new JSONArray();
                }else{
                    ja=new JSONArray(jaString);

                }
                data1.put("usertype",usertype);

                ja.put(data1);
                MyApplication.editor.putString(MyApplication.ALL_LOGS,ja.toString());
                MyApplication.editor.commit();

            } catch (JSONException e) {
                e.printStackTrace();
            }

            super.onPostExecute(res);
        }

        @Override
        protected Object doInBackground(Object... params) {
            OutStorageRequest outStorageRequest = (OutStorageRequest) params[0];

            String res = Utils.postCommit(getString(R.string.first_url) + getString(R.string.addDepotHeadAndDetailCheck), outStorageRequest);
            return res;
        }
    }
    /**
     * 经销商出库请求
     *
     * @author tjh
     */
    private class OutStorageJXSAsyn extends MyAsyncTask {

        @Override
        protected void onPostExecute(Object res) {
//            progressDialog.dismiss();
            //获取提交请求
            String str=Utils.toJSON(outStorageRequest);
            JSONObject data1 =null;
            if (res == null || res.equals("")) {
                data1 = Utils.getDiffData(0,"扫码出库", "与服务器通讯失败", username, str);
                Toast.makeText(NewOutStorageActivity.this, getString(R.string.server_error), Toast.LENGTH_LONG).show();
            } else {
                try {
                    JSONObject jo = new JSONObject(res.toString());
                    data1 = Utils.getDiffData(jo.getInt("code"),"扫码出库", jo.getString("msg"), username, str);

                } catch (Exception e) {
                    e.printStackTrace();
                    data1 = Utils.getDiffData(0, "扫码出库","数据解析失败！", username, str);
                }
            }
            String jaString = MyApplication.mSettings.getString(MyApplication.ALL_LOGS, "");
            try {
                JSONArray ja=null;
                if(StringUtils.isEmpty(jaString)){
                    ja=new JSONArray();
                }else{
                    ja=new JSONArray(jaString);

                }
                data1.put("usertype",usertype);

                ja.put(data1);
                MyApplication.editor.putString(MyApplication.ALL_LOGS,ja.toString());
                MyApplication.editor.commit();

            } catch (JSONException e) {
                e.printStackTrace();
            }
            super.onPostExecute(res);
        }

        @Override
        protected Object doInBackground(Object... params) {
            OutStorageRequest outStorageRequest = (OutStorageRequest) params[0];
            String res = Utils.postCommit(getString(R.string.first_url) + getString(R.string.supplierrOut), outStorageRequest);
            return res;
        }
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        //手动退出
        if(isHeadBack){
            //如果手动退出需要加一个缓存把退库信息缓存到本地
            dataSave.setDataList(userId+MyApplication.NEW_OUT_STORAGE,codeStringList);
        }else{
            dataSave.setDataList(userId+MyApplication.NEW_OUT_STORAGE,new ArrayList<String>());
        }
        dealerList.clear();
//        xMListViewAdapter = null;
        boxCodeList.clear();
        boxCodeList = null;
    }

    @Override
    public void onResume() {
        isVisible = true;
        super.onResume();
        //registerReceiver(new String[] { getString(R.string.SCAN_ACTION) });
        registerIDataReceiver(new String[]{getString(R.string.SCAN_IDATA_ACTION)});
    }

    @Override
    protected void onPause() {
        isVisible = false;
        super.onPause();
    }

    @Override
    protected void handleReceiver(Context context, Intent intent) {
        super.handleReceiver(context, intent);
        if (isVisible) {
            if (getString(R.string.SCAN_ACTION).equals(intent.getAction())) {
                String scanStatus = intent.getStringExtra(getString(R.string.SCAN_STATE));
                if ("ok".equals(scanStatus)) {
                    // 成功
                    String resultStr = intent.getStringExtra(getString(R.string.DATA_STRING)).trim();
                    dhEdit.setText(resultStr);
                } else {
                    // 失败如超时等
                    showToast(getString(R.string.scan_timeout_warn), 0);
                }
            }
        }
    }

    @Override
    protected void handleIDataReceiver(Context context, Intent intent) {
        // TODO Auto-generated method stub
        super.handleIDataReceiver(context, intent);
        if (isVisible) {
            if (getString(R.string.SCAN_IDATA_ACTION).equals(intent.getAction())) {
                String scanResult = intent.getStringExtra("value");
                if (scanResult.length() > 0) {
                    dhEdit.setText(scanResult);
                } else {
                    // 失败如超时等
                    showToast(getString(R.string.scan_timeout_warn), 0);
                }
            }
        }
    }
}